using System;
using System.Collections.Generic;
using System.Linq;
using ApiProject.Api.Data;
using ApiProject.Api.Entity;
using ApiProject.Api.PramaModel;
using ApiProject.Api.Repository;
using ApiProject.Api.Uitls;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

//后台用户登录
namespace ApiProject.Api.Controllers
{

    //管理员登录并获取token
    [ApiController]
    [Route("[controller]")]
    public class BackgroundLoginController : ControllerBase
    {


        private IRepository<Users> _usersRepository;
        private IRepository<UserInfo> _userinfoRepository;
        private IRepository<Roles> _roleRepository;


        private Token _tokenParameter;

        private readonly IConfiguration _configuration;

        public BackgroundLoginController(
            IConfiguration configuration,

            IRepository<Users> usersRepository,
            IRepository<Roles> roleRepository,
            IRepository<UserInfo> userinfoRepository


        )
        {

            _configuration = configuration;
            _tokenParameter =
                _configuration.GetSection("TokenParameter").Get<Token>();
            _usersRepository = usersRepository;
            _userinfoRepository = userinfoRepository;

            _roleRepository = roleRepository;

        }




         // 获取所有角色
        [HttpGet]
        public dynamic GetRoles()
        {

       
            var roles = _roleRepository.Table.Where(x => x.IsDelete == false && x.IsEnable==true ).Where(o=>!o.RoleName.Contains("用")).ToList();
             
            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = roles,
                Msg = "查找角色成功"
            });
        }





          //后台用户修改密码
        [HttpPost("{id}")]
        public dynamic updataUserpass(int id, NewUserPass model)
        {
            var pass = model.BeforeuserPass.Trim();
            var password = model.Password.Trim();
            var CheckPass = model.CheckPass.Trim();
            var userpass = _usersRepository.Table.Where(x => x.Password == pass).FirstOrDefault();
            System.Console.WriteLine(userpass);
            if (userpass != null)
            {
                var user = _usersRepository.GetById(id);
                if (user != null)
                {
                    user.Password = password;

                    user.UpdateTime = DateTime.Now;
                    _usersRepository.Update(user);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = user,
                        Msg = string.Format("修改成功，请注意查收")
                    });
                }
                else
                {
                    return JsonHelper.Serialize(new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "指定Id的用户不存在，请确认后重试"
                    });
                }


            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "原密码错误，请确认后重试"
                });
            }

        }


        // 后台用户 修改 用户信息
        // Put:/BackgroundLogin/alter_userinfo/{id}
        //参数：id = userId userInfo
        [HttpPost, Route("alteruserinfo/{id}")]
        public dynamic alterUserInfo(int id, NewUserInfo newUserInfo)
        {

            var userInfo = _userinfoRepository.GetById(id);

            if (userInfo != null)
            {

                userInfo.NickName = newUserInfo.NickName;
                userInfo.Sex = newUserInfo.Sex;
                userInfo.Birthday = newUserInfo.Birthday;
                userInfo.Address = newUserInfo.Address;
                userInfo.SelfIntroduction = newUserInfo.SelfIntroduction;
                userInfo.Dzyx=newUserInfo.Dzyx;
                userInfo.Telephone=newUserInfo.Telephone;
                userInfo.UpdateTime=DateTime.Now;


                _userinfoRepository.Update(userInfo);

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = userInfo,
                    Msg = "用户信息修改成功"
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "用户信息修改失败"
                });
            }

        }





        // 后台用户 修改 商户信息
        // Put:/BackgroundLogin/alter_userinfo/{id}
        //参数：id = userId userInfo
        [HttpPost, Route("alterStoreInfo/{id}")]
        public dynamic alterStoreInfo(int id, NewUserInfo newUserInfo)
        {

            var userInfo = _userinfoRepository.GetById(id);

            if (userInfo != null)
            {

                userInfo.NickName = newUserInfo.NickName;
                userInfo.Birthday = newUserInfo.Birthday;
                userInfo.Address = newUserInfo.Address;
                userInfo.SelfIntroduction = newUserInfo.SelfIntroduction;
                userInfo.Dzyx=newUserInfo.Dzyx;
                userInfo.Telephone=newUserInfo.Telephone;
                userInfo.UpdateTime=DateTime.Now;


                _userinfoRepository.Update(userInfo);

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = userInfo,
                    Msg = "用户信息修改成功"
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "用户信息修改失败"
                });
            }

        }




        // 后台显示当前登录用户的名片信息
        // Get: /BackgroundLogin/get_userinfo/{id}
        [HttpGet, Route("getUserInformation/{id}")]
        public dynamic getUserInfo(int id)
        {

            var userInfo = _userinfoRepository.GetById(id);

            if (userInfo != null)
            {
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = userInfo,
                    Msg = "获取用户信息成功"
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "获取用户信息失败"
                });
            }
        }










        //管理员登录并获取token
        // Post:/BackgroundLogin/login
        [AllowAnonymous]
        [HttpPost, Route("login")]
        public dynamic AdminLogin(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var roleid =model.RolesId;

          
            var admin = _usersRepository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();
            if (admin == null)
            {
                return JsonHelper
                            .Serialize(new
                            {
                                Code = 1000,
                                Data = "",
                                Msg = "账号或密码错误"
                            });
            }
            else
            {
                var role = _roleRepository.Table.Where(x => x.Id == admin.RolesId).FirstOrDefault();
                var roleName = role.RoleName;

                Console.WriteLine(admin);



                //查找不到
                if (admin == null)
                {
                    return JsonHelper
                        .Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "用户名或密码错误,请重新输入"
                        });
                }
                else
                {
                      var roles = _roleRepository.Table.Where(x => x.Id==roleid).FirstOrDefault();
                    if (roles.RoleName==roleName)
                    {
                        //判断管理员是否删除
                        if (admin.IsDelete == false)
                        {
                            //判断管理员是否启用
                            if (admin.IsEnable == true)
                            {
                                var token = TokenHelper.GetToken(_tokenParameter, admin);
                                var refreshToken = "123456";
                                var admininfo = _userinfoRepository.GetById(admin.Id);


                                return JsonHelper
                                    .Serialize(new
                                    {
                                        Code = 200,
                                        Data =
                                            new
                                            {
                                                Token = token,
                                                RefreshToken = refreshToken,
                                                AdminName = username,
                                                Id = admin.Id,
                                                RealName = admininfo.NickName
                                            },
                                        Msg = string.Format("{0}",roles.RoleName)
                                    });
                            }
                            else
                            {
                                return JsonHelper
                                    .Serialize(new
                                    {
                                        Code = 1000,
                                        Data = "",
                                        Msg = "该管理员已被禁用，请联系超级管理员"
                                    });
                            }
                        }
                        else
                        {
                            return JsonHelper
                                .Serialize(new
                                {
                                    Code = 1000,
                                    Data = "",
                                    Msg = "该管理员已被删除，请联系超级管理员"
                                });
                        }
                    }
                    else
                    {
                        return JsonHelper
                             .Serialize(new
                             {
                                 Code = 1000,
                                 Data = "",
                                 Msg = "没有该角色选择，请重试"
                             });
                    }
                }




            }
        }
    }
}
